package bc.swim2.web.servlet;

import java.io.IOException;

import javax.naming.Context;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bc.swim2.ejb.entity.RegisteredUser;
import bc.swim2.ejb.session.FeedbackManagerBeanRemote;

/**
 * Servlet implementation class FeedbackServlet
 */
public class FeedbackServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public FeedbackServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (request.getParameter("methodName").equals("addFeedback")) {
			addFeedback(request, response);
		}
	}

	private void addFeedback(HttpServletRequest request,
			HttpServletResponse response) {

		RegisteredUser sender = null;
		RegisteredUser receiver = null;
		boolean score = false;
		int abilityId;

		try {

			HttpSession session = request.getSession(true);
			Context ctx = (Context) session.getAttribute("ctx");

			sender = (RegisteredUser) session
					.getAttribute("currentSessionUser");
			receiver = (RegisteredUser) session.getAttribute("profileUser");
			if (request.getParameter("score").equals("positive"))
				score = true;
			else
				score = false;

			abilityId = Integer.parseInt(request
					.getParameter("selectedAbilityId"));

			String description = request.getParameter("description");
			Object ref2 = ctx.lookup("FeedbackManagerBean/remote");
			FeedbackManagerBeanRemote fm = (FeedbackManagerBeanRemote) ref2;
			if (description.equalsIgnoreCase("mottola calcavecchia")) {
				session.setAttribute("nothingSpecial", true);}
			fm.insertFeedback(sender.getId(), receiver.getId(), score,
					abilityId, description);
			response.sendRedirect("MainServlet?to=Profile");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
